package com.hebeiboruan.dictionaries.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.hebeiboruan.common.exception.CommonException;
import com.hebeiboruan.common.exception.ServiceResultEnum;
import com.hebeiboruan.entity.system.Dictionaries;
import com.hebeiboruan.dictionaries.service.DictionariesService;
import org.springframework.beans.factory.annotation.Value;

import java.util.ArrayList;

public class DictionariesListener implements ReadListener<Dictionaries> {

        @Value("${project.batchCount}")
        private static  int BATCH_COUNT;
        private ArrayList<Dictionaries> list=new ArrayList<>(BATCH_COUNT);
        private DictionariesService dictionariesService;

        public DictionariesListener(DictionariesService dictionariesService) {
            this.dictionariesService = dictionariesService;
        }

        @Override
        public void invoke(Dictionaries dictionaries, AnalysisContext analysisContext) {
            list.add(dictionaries);
            if(list.size()>BATCH_COUNT){
                save();
            }
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        save();
        }
        private void save(){
        try{
            dictionariesService.saveBatch(list);
            list= ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }catch (Exception e){
            throw new CommonException(ServiceResultEnum.BATCH_INSERT_ERROR,e);
        }

        }
}

